package org.mtmi.io.controls;

import java.io.IOException;

import net.n3.nanoxml.IXMLElement;

import org.mtmi.io.ReaderError;
import org.mtmi.io.SceneReader;
import org.mtmi.io.SceneWriter;
import org.mtmi.io.XMLReader;
import org.mtmi.io.XMLWriter;
import org.mtmi.ui.IAdaptable;
import org.mtmi.ui.controls.AbstractRangeValueControl;
import org.mtmi.ui.controls.AbstractValueControlledControl;
import org.mtmi.ui.controls.Control;
import org.mtmi.ui.controls.IValueGenerator;
import org.mtmi.ui.controls.listeners.ValueChangedListener;

/**
 * In addition to {@link ControlIO}, save {@link AbstractValueControlledControl} features:
 * <ul>
 * <li> the value generator controller if it's a control.
 * </ul>
 * note: the value is not saved.
 */
public class ValueControlledControlIO extends ControlIO
{
	public static final String E_VALUE_CONTROLLER ="valueController"; //$NON-NLS-1$
	public static final String A_ID="id"; //$NON-NLS-1$
	public static final String A_CID="cid"; //$NON-NLS-1$
	
	@Override
	public void writeControl( Control c, XMLWriter w, SceneWriter sw ) throws IOException 
	{
		super.writeControl( c, w, sw );
		
		if( c instanceof AbstractValueControlledControl ) 
		{
			AbstractValueControlledControl avc = (AbstractValueControlledControl)c;
		
			//value controller
			IValueGenerator vg = avc.getValueController();
			Control cvg = null;
			if( vg instanceof IAdaptable ) {
				cvg = (Control)( (IAdaptable)vg).getAdapter( Control.class, null );
			}
			if( cvg != null ) {
				boolean ai = w.setAttributeIndented( false );
				w.startElement( E_VALUE_CONTROLLER );
				w.addAttr( A_ID, sw.getControlId( cvg ) );
				w.addAttr( A_CID, avc.getValueControllerConnectionId(), (String)null );
				w.endElement( E_VALUE_CONTROLLER );
				w.setAttributeIndented( ai );
			}
		}
	}
	
	@Override
	public void readControl( Control c, IXMLElement element, XMLReader r, SceneReader sr ) throws ReaderError 
	{
		super.readControl(c, element, r, sr);
		
		if( c instanceof AbstractValueControlledControl ) 
		{
			AbstractValueControlledControl avr = (AbstractValueControlledControl)c;
			
			
			//value controller:
			IXMLElement e = r.getElement( element, E_VALUE_CONTROLLER, false );
			if( e!=null ) {
				int id = r.getAttrInt( e, A_ID );
				String cid = r.getAttr( e, A_CID, (String)null );
				Control control = sr.getControl( id );
				if( control!=null ) {
					IValueGenerator vg = (IValueGenerator)control.getAdapter( IValueGenerator.class, cid );
					if( vg!=null ) {
						avr.setValueController( vg, cid );
					}
				}
			}
		}
	}
}
